/********************************************
 * 功能说明: Message实体与DTO之间接口数据转换实现
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员: Frank
 * 开发时间: 2019-10-17 18:02:38
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.message.converter;

import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.message.common.errorcode.MessageErrorCode;
import com.spring.arch.message.repository.MessageRepository;
import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.message.dto.MessageDTO;
import com.spring.arch.message.model.Message;
import com.spring.arch.message.repository.MessageRepository;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.spring.arch.message.common.errorcode.MessageErrorCode.E1016000001;

/**
 * Message实体与DTO之间接口数据转换实现
 *
 * @author Frank
 * @version 1.0.0.1
 * @since 2019-10-17 18:02:38
 */
@Component
public class MessageConverter extends AbstractConverter<Message, MessageDTO> {

    @Autowired
    private MessageRepository messageRepository;

    @Override
    public Message toModel(@NonNull final MessageDTO dto) {
        if(dto.isNew()) {
            return constructModel(dto);
        } else {
            return updateModel(dto);
        }
    }

    @Override
    public MessageDTO toDTO(@NonNull final Message model) {
        final MessageDTO dto = new MessageDTO();

        dto.setId(model.getId());
        dto.setMobile(model.getMobile());
        dto.setBusinessType(model.getBusinessType());
        dto.setType(model.getType());

        this.convertCommonToDTO(model, dto);

        return dto;
    }

    /**
     * 构建新Model
     */
    private Message constructModel(final MessageDTO dto) {
        final Message model = new Message();
        this.dtoToModel(dto, model);
        return model;
    }

    /**
     * 更新Model
     */
    private Message updateModel(final MessageDTO dto) {
        final Message model = this.messageRepository.findById(dto.getId())
                .orElseThrow(() -> ExceptionHolder.serviceException(MessageErrorCode.E1016000001, Message.class.getSimpleName()));
        this.dtoToModel(dto, model);
        return model;
    }

    private void dtoToModel(final MessageDTO dto, final Message model) {
        model.setMobile(dto.getMobile());
        model.setBusinessType(dto.getBusinessType());
        model.setType(dto.getType());

    }
}
